<template>
  <div class="xq-form-wrapper page-miH page-bgBack p24">
    <div class="mb16">
      <selectGroup @upDate="upDate" />
    </div>
    <a-spin :spinning="spinning" class="xq-form-content" style="margin-top: 24px">
      <TableBody
        ref="TableBody"
        tableName="taxCalculateReport"
        :selectedRowKeys.sync="selectedRowKeys"
        :source="tableData"
        :headerRowID="'sortable_list'"
        :selectHead="false"
        :selection="!stateActive ? true : false"
        selectionSlot
        action
        @onClose="handleCancelTable"
        @onSearch="handleSearch"
      >
        <template slot="search">
          <a-input-search v-model="searchName" style="width: 240px" placeholder="姓名/手机号" allow-clear @search="onSearchName" />
          <a-select label="任职受雇类型" allow-clear placeholder="请选择任职受雇类型" style="width: 100%" v-model="employmentType">
            <a-select-option v-for="(item, index) in employmentTypeArr" :key="index" :value="item.value">{{ item.label }}</a-select-option>
          </a-select>
          <a-select label="报送状态" allow-clear placeholder="请选择报送状态" style="width: 100%" v-model="submissionState">
            <a-select-option v-for="(item, index) in submissionStateArr" :key="index" :value="item.value">{{ item.label }}</a-select-option>
          </a-select>
          <a-select label="身份验证状态" allow-clear placeholder="请选择身份验证状态" style="width: 100%" v-model="authenticationState">
            <a-select-option v-for="(item, index) in validationStateArr" :key="index" :value="item.value">{{ item.label }}</a-select-option>
          </a-select>
          <a-range-picker label="任职受雇日期" valueFormat="YYYY-MM-DD" v-model="Time1" allowClear />
          <a-range-picker label="离职日期 " valueFormat="YYYY-MM-DD" v-model="Time2" allowClear />
          <a-select label="信息是否完备" allow-clear placeholder="请选择信息是否完备" style="width: 100%" v-model="isComplete">
            <a-select-option v-for="(item, index) in CompletenessInformationArr" :key="index" :value="item.value">{{
              item.label
            }}</a-select-option>
          </a-select>
        </template>
        <template slot="action-btn">
          <div v-if="$route.meta.tabType == '1'">
            <a-button
              class="mr12"
              v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.daibaosong:export')"
              :disabled="!tableData.length"
              @click="onDownload"
              >导出</a-button
            >
            <div style="display: inline-block" v-if="!stateActive">
              <a-popover style="margin-right: 0" v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.daibaosong:huoqubaosongjieguo')">
                <template slot="content">
                  <span style="font-size: 14px">请进行报送后，再点击获取结果</span>
                </template>
                <a-button class="mr12" type="primary" disabled>获取报送结果</a-button>
              </a-popover>
              <a-dropdown :disabled="!tableData.length" v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.daibaosong:baosong')">
                <a-button type="primary">报送</a-button>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a @click="onSubmitAll('submit')">一键报送</a>
                  </a-menu-item>
                  <a-menu-item @click="selectSubmit()">
                    <a>选择报送</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </div>
            <div v-else style="display: inline-block">
              <a-button
                class="mr12"
                v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.daibaosong:huoqubaosongjieguo')"
                :disabled="!tableData.length"
                :loading="feedBackLoading"
                @click="onFeedBack('submit')"
                >获取报送结果</a-button
              >
              <a-popover style="margin-right: 0" v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.daibaosong:baosong')">
                <template slot="content">
                  <span style="font-size: 14px">请获取上次报送结果后，再进行下次报送</span>
                </template>
                <a-button type="primary" disabled>报送</a-button>
              </a-popover>
            </div>
          </div>
          <div v-if="$route.meta.tabType == '2'">
            <a-button
              class="mr12"
              v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.yibaosong:export')"
              :disabled="!tableData.length"
              @click="onDownload"
              >导出</a-button
            >
            <div style="display: inline-block" v-if="!stateActive">
              <a-popover style="margin-right: 0" v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.yibaosong:baosongfankui')">
                <template slot="content">
                  <span style="font-size: 14px">请进行报送后，再点击获取结果</span>
                </template>
                <a-button class="mr12" type="primary" disabled>获取报送结果</a-button>
              </a-popover>
              <a-button
                class="mr12"
                v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.yibaosong:tingzhibaosong')"
                :disabled="!selectedRowKeys.length"
                @click="visible = true"
                >停止报送</a-button
              >
              <a-dropdown :disabled="!tableData.length" v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.yibaosong:update')">
                <a-button type="primary">信息更新</a-button>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a @click="onSubmitAll('update')">一键报送</a>
                  </a-menu-item>
                  <a-menu-item @click="selectSubmit()">
                    <a>选择报送</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </div>
            <div v-else style="display: inline-block">
              <a-button
                class="mr12"
                v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.yibaosong:baosongfankui')"
                :disabled="!tableData.length"
                :loading="feedBackLoading"
                @click="onFeedBack(textFeedBack)"
                >获取报送结果</a-button
              >
              <a-popover v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.yibaosong:tingzhibaosong')">
                <template slot="content">
                  <span style="font-size: 14px">请获取上次报送结果后，再进行下次报送</span>
                </template>
                <a-button class="mr12" disabled>停止报送</a-button>
              </a-popover>
              <a-popover v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.yibaosong:update')">
                <template slot="content">
                  <span style="font-size: 14px">请获取上次报送结果后，再进行下次报送</span>
                </template>
                <a-button type="primary" disabled>信息更新</a-button>
              </a-popover>
            </div>
          </div>
          <div v-if="$route.meta.tabType == '3'">
            <a-button
              class="mr12"
              v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.tingzhibaosong:export')"
              :disabled="!tableData.length"
              @click="onDownload"
              >导出</a-button
            >
            <div style="display: inline-block" v-if="!stateActive">
              <a-popover style="margin-right: 0" v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.tingzhibaosong:baosongfankui')">
                <template slot="content">
                  <span style="font-size: 14px">请进行报送后，再点击获取结果</span>
                </template>
                <a-button class="mr12" type="primary" disabled>获取报送结果</a-button>
              </a-popover>
              <a-dropdown :disabled="!tableData.length" v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.tingzhibaosong:huifubaosong')">
                <a-button type="primary">恢复报送</a-button>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a @click="onSubmitAll('recover')">一键报送</a>
                  </a-menu-item>
                  <a-menu-item @click="selectSubmit()">
                    <a>选择报送</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </div>
            <div v-else style="display: inline-block">
              <a-button
                class="mr12"
                :disabled="!tableData.length"
                v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.tingzhibaosong:baosongfankui')"
                :loading="feedBackLoading"
                @click="onFeedBack('recover')"
                >获取报送结果</a-button
              >
              <a-popover style="margin-right: 0" v-if="$hasPermission('zhinengsuanshui:renyuanbaosong.tingzhibaosong:huifubaosong')">
                <template slot="content">
                  <span style="font-size: 14px">请获取上次报送结果后，再进行下次报送</span>
                </template>
                <a-button type="primary" disabled>恢复报送</a-button>
              </a-popover>
            </div>
          </div>
        </template>
        <template slot="selection-btn">
          <div class="pr24" style="text-align: right; width: calc(100% - 24px); display: flex; justify-content: center; top: 15px">
            <a-button class="mr12" @click="$refs.TableBody.TBFclose()">取消</a-button>
            <a-button type="primary" @click="onSubmit">报送</a-button>
          </div>
        </template>

        <template>
          <XqTable
            :customize="FormJson['config']['table']['customize']"
            :scroll="{ x: columns.length * 150 }"
            :pagination="false"
            :dataSource="tableData"
            :columns="columns"
            :rowSelection="
              FormJson['config']['table']['extend']['batch']
                ? {
                    selectedRowKeys: selectedRowKeys,
                    onChange: onSelectChange
                  }
                : null
            "
          >
            <template v-for="(col, index) in columns" v-slot:[`xq_${col.dataIndex}`]>
              <span :key="index">{{ col.customTitle }}</span>
            </template>
            <!-- eslint-disable-next-line prettier/prettier v-slot:[`xq_${col.dataIndex}`]-->
            <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
              <div v-if="col.dataIndex === 'status'" :key="index">{{ peopleStatusJson[text] }}</div>
              <div v-else-if="col.dataIndex === 'employmentType'" :key="index">{{ employmentTypeJson[text] }}</div>
              <div v-else-if="col.dataIndex === 'submissionState'" :key="index">
                <a-tag color="#386FD7" v-if="submissionStateJson[text] === '报送中'">{{ submissionStateJson[text] }}</a-tag>
                <a-tag color="#FE5770" v-else-if="submissionStateJson[text] === '报送失败'">{{ submissionStateJson[text] }}</a-tag>
                <a-tag color="#24CDAA" v-else-if="submissionStateJson[text] === '报送成功'">{{ submissionStateJson[text] }}</a-tag>
                <span v-else>{{ submissionStateJson[text] }}</span>
              </div>
              <div v-else-if="col.dataIndex === 'authenticationState'" :key="index">{{ authenticationStateJson[text] }}</div>
              <div v-else-if="col.dataIndex === 'isComplete'" :key="index">{{ text ? "是" : "否" }}</div>
              <div v-else-if="col.dataIndex === 'submissionDate'" :key="index">
                {{ text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : "--" }}
              </div>
              <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" />
            </template>
          </XqTable>
        </template>
      </TableBody>
      <div class="xq-form-content-pagination">
        <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
        <a-pagination
          v-model="pageNo"
          :total="total"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :page-size-options="['10', '20', '50', '100']"
          :page-size="pageSize"
          @change="onPageChange"
          @showSizeChange="onPageSizeChange"
        />
      </div>
    </a-spin>
    <popUp ref="popVal"></popUp>
    <stopReport :visible.sync="visible" :recordIds="selectedRowKeys" :companyAuthId="id" @upDate="stopOnGetPageSubmit" />
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";
import { getPageSubmit, postSubmitFeedBack, getActiveByType } from "./api";
import {
  peopleStatusArr,
  employmentTypeArr,
  submissionStateArr,
  validationStateArr,
  authenticationStateArr,
  CompletenessInformationArr
} from "../staticData";
import selectGroup from "./component/selectGroup";
import stopReport from "./component/stopReport";
import popUp from "./component/popUp";
const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});
export default {
  mixins: [curdMixin],
  components: {
    selectGroup,
    stopReport,
    popUp
  },
  data() {
    return {
      textFeedBack: sessionStorage.getItem("textFeedBack") || "update",
      visible: false,
      searchName: "",
      employmentType: undefined,
      submissionState: undefined,
      authenticationState: undefined,
      selects: undefined,
      isComplete: undefined,
      Time1: [],
      Time2: [],
      spinning: false,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      selectedRowKeys: [],
      tagsSelect: 0,
      id: "",
      peopleStatusArr,
      employmentTypeArr,
      submissionStateArr,
      authenticationStateArr,
      CompletenessInformationArr,
      validationStateArr,
      peopleStatusJson: {},
      employmentTypeJson: {},
      submissionStateJson: {},
      authenticationStateJson: {},
      CompletenessInformationJson: {},
      feedBackLoading: false,
      stateActive: null
    };
  },
  created() {
    this.getVal();
  },
  methods: {
    stopFun() {
      this.visible = true;
    },
    getActiveByTypeFunTwo() {
      const update = getActiveByType({
        requestType: 1,
        submitType: "update",
        companyAuthId: sessionStorage.getItem("taxCalculate/selectedValue")
      });
      const stop = getActiveByType({
        requestType: 1,
        submitType: "stop",
        companyAuthId: sessionStorage.getItem("taxCalculate/selectedValue")
      });
      Promise.all([update, stop])
        .then((result) => {
          if (!result[0].data && !result[1].data) {
            this.stateActive = null;
          } else {
            if (result[0].data) {
              this.stateActive = result[0].data;
              this.textFeedBack = "update";
            } else if (result[1].data) {
              this.stateActive = result[1].data;
              this.textFeedBack = "stop";
            }
          }
        })
        .catch((error) => {
          console.log(error); // 失败了，打出 '失败'
        });
    },
    getActiveByTypeFun() {
      const data = {
        requestType: 1,
        submitType: this.$route.meta.tabType === "1" ? "submit" : this.$route.meta.tabType === "3" ? "recover" : this.textFeedBack,
        companyAuthId: sessionStorage.getItem("taxCalculate/selectedValue")
      };
      getActiveByType(data)
        .then((res) => {
          this.stateActive = res.data;
          // console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    selectSubmit() {
      this.$refs.TableBody.selectionBtnLock = true;
    },
    getVal() {
      peopleStatusArr.map((e) => {
        this.peopleStatusJson[e.value] = e.label;
      });
      employmentTypeArr.map((e) => {
        this.employmentTypeJson[e.value] = e.label;
      });
      submissionStateArr.map((e) => {
        this.submissionStateJson[e.value] = e.label;
      });
      authenticationStateArr.map((e) => {
        this.authenticationStateJson[e.value] = e.label;
      });
      CompletenessInformationArr.map((e) => {
        this.CompletenessInformationJson[e.value] = e.label;
      });
    },
    upDate(e) {
      this.selectedRowKeys = [];
      this.id = e;
      this.onGetPageSubmit();
    },
    handleSearch() {
      this.selectedRowKeys = [];
      this.pageNo = 1;
      this.onGetPageSubmit();
    },
    handleCancelTable() {
      this.employmentType = undefined;
      this.submissionState = undefined;
      this.authenticationState = undefined;
      this.Time1 = [];
      this.Time2 = [];
      this.selectedRowKeys = [];
      this.pageNo = 1;
      this.onGetPageSubmit();
    },
    onSearchName() {
      this.selectedRowKeys = [];
      this.pageNo = 1;
      this.onGetPageSubmit();
    },
    stopOnGetPageSubmit() {
      sessionStorage.setItem("textFeedBack", "stop");
      this.textFeedBack = sessionStorage.getItem("textFeedBack");
      console.log("textFeedBack", sessionStorage.getItem("textFeedBack"), this.textFeedBack);
      this.onGetPageSubmit();
    },
    async onGetPageSubmit() {
      if (this.id) {
        try {
          this.spinning = true;
          const params = {
            authorityId: this.id,
            selectName: this.searchName || null,
            pageNo: this.pageNo,
            pageSize: this.pageSize,
            isComplete: this.isComplete,
            tabType: this.$route.meta.tabType,
            employmentType: this.employmentType,
            submissionState: this.submissionState,
            authenticationState: this.authenticationState,
            employedDateStart: this.Time1[0],
            employedDateEnd: this.Time1[1],
            resignDateStart: this.Time2[0],
            resignDateEnd: this.Time2[1],
            "orders[0].property": "gmtCreate",
            "orders[0].desc": true
          };
          const { data } = await getPageSubmit(params);
          this.tableData = data?.entities || [];
          this.total = data?.entityCount || 0;
          this.selectedRowKeys = [];
          if (this.$route.meta.tabType === "2") {
            this.getActiveByTypeFunTwo();
          } else {
            this.getActiveByTypeFun();
          }
          setTimeout(() => (this.spinning = false), 500);
        } catch (err) {
          console.log("error log --> ", err);
          this.tableData = [];
          this.total = 0;
          setTimeout(() => (this.spinning = false), 500);
        }
      } else {
        const that = this;
        this.$warning({
          title: "请先创建扣缴义务人",
          onOk() {
            that.$router.push("/taxCalculate/management");
          }
        });
      }
    },
    onPageChange(page) {
      this.selectedRowKeys = [];
      this.pageNo = page;
      this.onGetPageSubmit();
    },
    onPageSizeChange(current, pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.onGetPageSubmit();
    },
    onSubmitAll(v) {
      sessionStorage.setItem("taxCalculate/authorityId", this.id);
      sessionStorage.setItem("taxCalculate/tabType", this.$route.meta.tabType);
      const val = v || "";
      sessionStorage.setItem("taxCalculate/submitType", val);
      if (v === "update") {
        sessionStorage.setItem("textFeedBack", "update");
      }
      this.$router.push({
        name: "reportConfirm"
      });
    },
    onSubmit() {
      sessionStorage.setItem("taxCalculate/authorityId", this.id);
      sessionStorage.setItem("taxCalculate/tabType", this.$route.meta.tabType);
      const selectedRowKeys = JSON.stringify(this.selectedRowKeys);
      sessionStorage.setItem("taxCalculate/reportIdArr", selectedRowKeys);

      sessionStorage.setItem("textFeedBack", "update");
      let val = "";
      if (this.$route.meta.tabType === "1") val = "submit";
      if (this.$route.meta.tabType === "2") val = "update";
      if (this.$route.meta.tabType === "3") val = "recover";
      sessionStorage.setItem("taxCalculate/submitType", val);
      this.$router.push({
        name: "reportConfirm"
      });
    },
    onStop(e) {
      console.log(e);
      // sessionStorage.setItem("taxCalculate/authorityId", this.id);
      // sessionStorage.setItem("taxCalculate/tabType", this.$route.meta.tabType);
      // const selectedRowKeys = JSON.stringify(this.selectedRowKeys);
      // sessionStorage.setItem("taxCalculate/reportIdArr", selectedRowKeys);
      // this.$router.push({
      //   name: "reportConfirm"
      // });
    },
    async onFeedBack(e) {
      console.log(e);
      try {
        this.feedBackLoading = true;
        const data = await postSubmitFeedBack({
          companyAuthId: this.id,
          submitType: e,
          tabType: this.$route.meta.tabType
        });
        this.$refs.popVal.showModal(data, "获取报送结果");
        // this.$notification.success({ message: "操作成功" });
        this.onGetPageSubmit();
        this.feedBackLoading = false;
      } catch (err) {
        this.feedBackLoading = false;
        console.log("error log --> ", err);
      }
    },
    onDownload() {
      const token = this.$store.state.auth.token;
      const columns = this.columns.map((e) => {
        const json = {
          title: e.customTitle,
          dataIndex: e.dataIndex
        };
        if (e.dateFormat) json.dateFormat = e.dateFormat;
        return json;
      });
      let name = "";
      if (this.$route.meta.tabType === "1") name = "待";
      if (this.$route.meta.tabType === "2") name = "已";
      if (this.$route.meta.tabType === "3") name = "停止";
      axios({
        url: `/tax/api/v1/employeeRecords/export`,
        data: {
          authorityId: this.id,
          selectName: this.searchName || null,
          tabType: this.$route.meta.tabType,
          employmentType: this.employmentType,
          submissionState: this.submissionState,
          authenticationState: this.authenticationState,
          employedDateStart: this.Time1[0],
          employedDateEnd: this.Time1[1],
          resignDateStart: this.Time2[0],
          resignDateEnd: this.Time2[1],
          exportColumns: columns
        },
        paramsSerializer: (param) => {
          return qs.stringify(param, { indices: false });
        },
        method: "POST",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", `${name}报送人员数据表.xlsx`);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("error log --> ", err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.tags {
  display: flex;
  .tags-item {
    height: 32px;
    line-height: 32px;
    border-radius: 16px;
    font-weight: 400;
    color: #a6a8b4;
    background: #f4f6fa;
    padding: 0 18px;
    cursor: pointer;
  }
}
.tags-item-primary {
  color: var(--primary) !important;
  background: var(--primary30) !important;
}
</style>
